const {wsapilogSchema,mysql,sequelize} = require('./mysqlSequelize');
module.exports = (server , options) => {
  server.on('request', (req, res) => {
    let body;
    req.on('data', (data) => {
      body = body ? Buffer.concat([body, data]) : data;
    });
    req.on('end', async () => {
      var status= sequelize.connectionManager.state
      console.log('连接管理器状态:', sequelize.connectionManager.state);
      if (body) {
        if (req.originalReq.headers['content-type'].includes("json")){
           res_body=JSON.parse(body.toString('utf-8'))
           }
        wsapilogSchema.create({
            res_headers: JSON.stringify(req.headers),
            res_body: res_body,
            timestamp: Math.floor(Date.now() / 1000),
          }).then((request) => {
            console.log('请求和响应报文已保存:', request.toJSON());
          }).catch((error) => {
            console.error('保存请求和响应报文时发生错误:', error);
          });
//        if(authenticated.equals("authenticated")){
//          const oid=req.originalReq.id
//          var apilog=null;
//          apilog=await WSApiLog.findOne({ "req.id": oid }).exec();
//          if (!apilog){
//            apilog=new WSApiLog(req.originalReq)
//          }
//          if (req.originalReq.headers['content-type'].includes("json")){
//            apilog.res_body=JSON.parse(body.toString('utf-8'))
//          }
//          apilog.res_headers=req.headers
//          const timestamp = Math.floor(Date.now() / 1000);
//          apilog.create_time=timestamp
//          apilog.save()
//        }
        res.end(Buffer.from(body.toString(), 'utf-8'));
      } else {
        res.end();
      }
    });
  });
};
